<?php
/**
 * @ClassName: Address
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-10-11 15:41
 * @Version: V1.0.0
 */

namespace app\api\controller;

use app\common\logic\AddressLogic;
use app\common\logic\AmapLogic;
use app\common\model;
use tpext\areacity\api\model\Areacity;

class Address extends Api
{
    /**
     * 保存收货地址
     * @return \think\response\Json
     */
    function save()
    {
        $data = input();

        if ($data['is_h5']) {
            $res = AmapLogic::geo($data['select_address'] . $data['address']);
            if ($res['code'] == 1) {
                $data['longitude'] = $res['data']['longitude'];
                $data['latitude'] = $res['data']['latitude'];
            }
        }

        // 如果当前地址为默认地址，先把之前的地址重置为非默认
        if ($data['is_default']) {
            model\MemberAddress::where(['member_id' => $this->user_id, 'falg' => $data['falg']])->update([
                'is_default' => 0,
                'update_time' => date_now(),
            ]);
        }

        $add_data = [
            'member_id' => $this->user_id,
            'falg' => $data['falg'],
            'consignee' => $data['consignee'],
            'mobile' => $data['mobile'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'town' => $data['town'],
            'select_address' => $data['select_address'],
            'address' => $data['address'],
            'longitude' => $data['longitude'],
            'latitude' => $data['latitude'],
            'is_default' => $data['is_default'],
        ];

        if (isset($data['id']) && $data['id']) {
            //编辑
            $add_data['create_time'] = date_now();
            $add_data['update_time'] = date_now();
            $address_id = model\MemberAddress::where('id', $data['id'])->update($add_data);
            $address_id = $data['id'];
        } else {
            //新增
            $add_data['update_time'] = date_now();
            $address_id = model\MemberAddress::insertGetId($add_data);
        }

        if (!$address_id) {
            return json(['code' => 0, 'msg' => '保存失败', 'data' => $address_id]);
        }

        return json(['code' => 1, 'msg' => '保存成功', 'data' => $address_id]);
    }

    /**
     * 收货地址列表
     * @return \think\response\Json
     */
    function list()
    {
        $falg = input('falg', 'user');
        $skip = input('skip', 0);
        $limit = input('limit', 10);

        $where = [
            'falg' => $falg,
            'member_id' => $this->user_id,
        ];

        $list = model\MemberAddress::where($where)->order('is_default desc,update_time desc')->limit($skip, $limit)->select();

        $result = [
            'list' => $list,
            'is_more' => count($list) >= $limit,
        ];

        return json(['code' => 1, 'data' => $result]);
    }

    /**
     * 地址详情
     * @return \think\response\Json
     */
    function detail()
    {
        $id = input('id');

        $data = model\MemberAddress::get($id);

        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 删除收货地址
     * @return \think\response\Json
     */
    function del()
    {
        $id = input('id');

        $res = model\MemberAddress::where('id', $id)->update([
            'update_time' => date_now(),
            'delete_time' => date_now(),
        ]);

        if (!$res) {
            return json(['code' => 0, 'msg' => '删除失败']);
        }

        return json(['code' => 1, 'msg' => '删除成功']);
    }

    /**
     * 获取默认地址
     * @return \think\response\Json
     */
    function defaultAddress()
    {
        $address_id = input('address_id', 0);
        $falg = input('falg', 'user');

        if ($address_id) {
            $data = model\MemberAddress::get($address_id);
        } else {
            $where = [
                'falg' => $falg,
                'member_id' => $this->user_id,
            ];

            $list = model\MemberAddress::where($where)->order('is_default desc,update_time desc')->limit(0, 10)->select();

            if (count($list) > 0) {
                $data = $list[0];
            } else {
                $data = [];
            }
        }

        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 获取三级地区（省市区县）
     * @return \think\response\Json
     */
    function getThreeArea()
    {
        $need_cache = input('cache', 1); // 是否获取缓存:0最新,1缓存

        $list = AddressLogic::getThreeArea($need_cache);

        return json(["code" => 1, "msg" => "获取成功", "data" => $list]);
    }

    /**
     * 通过上级ID查询
     * @return \think\response\Json
     */
    function getAreaByPid()
    {
        $areaData = Areacity::where(['pid' => input('pid')])->fieldRaw('id as value,name as label')->select();
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $areaData]);
    }

    /**
     * 获取地区信息
     * @return \think\response\Json
     */
    function areacityInfo()
    {
        $id = input('id', 0);

        $data = Areacity::where('id', $id)->find();

        return json(['code' => 1, 'msg' => '获取成功', 'data' => $data]);
    }

}